//
//  WBHomeListViewModel.swift
//  微博Demo
//
//  Created by 花化华 on 2016/11/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SDWebImage

class WBHomeListViewModel: NSObject {
    /// viewModel数据源数组
    lazy var statusViewModesArray: [WBHomeViewModel] = []

    /// 获取微博数据
    func loadData (isPullDown: Bool, callBack: @escaping (_ success: Bool) -> ()) {
        
        //请求参数默认为0
        var since_id = "0"
        var max_id = "0"
        
        //判断是上拉,还是下拉
        if isPullDown {
            since_id = statusViewModesArray.first?.statusModel.id ?? "0"
        }else {
//            print(statusViewModesArray.last?.statusModel.id ?? "0")
            max_id = statusViewModesArray.last?.statusModel.id ?? "0"
        }
        
        WBNetworkTools.sharedManager.reqeustStatus(since_id: since_id, max_id: max_id, access_token: WBUserAccount.shared.access_token!, callBack: {
            
            (response) in
            //如果获取了微博数据
            if let statusDic = response as? [String: Any], let statusDicArray = statusDic["statuses"] as? [[String: Any]] {
                
                //创建一个临时的空数组
                var responseViewsModels: [WBHomeViewModel] = []
                
                //遍历微博字典数组, 做字典转模型的操作
                for dict in statusDicArray {
                    //字典转status模型
                    let model = WBStatusModel.yy_model(with: dict)
                    
                    //创建viewModel
                    let viewModel = WBHomeViewModel(statusModel: model!)
                    responseViewsModels.append(viewModel)
                }
                
                //把模型数据添加到数据源
                if isPullDown {
                    self.statusViewModesArray += responseViewsModels
                }else {
                    //??
                    responseViewsModels.removeFirst()
                    self.statusViewModesArray += responseViewsModels
                }
                
                //先处理单张图片的宽和高(异步操作), 完成后,再执行闭包
                self.dealWithSinglePicture(viewModelsArray: responseViewsModels, callBack: callBack)
                
            }else{
                callBack(false)
            }
            
        })
        
    }
    
    /// 处理**单张图片**, 处理完成之后, 再更新UI, reloadTableView   刚创建WBHomeViewModel已经处理过一次
    func dealWithSinglePicture (viewModelsArray: [WBHomeViewModel], callBack: @escaping (_ success: Bool) -> ()) {
        
//        callBack(false)
        //创建一个调度组
        let group = DispatchGroup()
        
        //找到所有的单张图片
        for viewModel in viewModelsArray {
            
            if let pic_urls = viewModel.picUrls, pic_urls.count == 1 {
                //入组
                group.enter()
                //生成url  ??
                let url = URL(string: (pic_urls.first?.thumbnail_pic)!)
                
                //下载单张图片
                SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (downloadImage, _, _, _, _) in
                    
                    //下载完成之后,设置viewModel中的pictureView的size
                    var size = (downloadImage?.size)!
                    size.width *= 2
                    size.height *= 2
                    viewModel.pictureViewSize = size
                    group.leave()
                })
            }
        }
        
        //所有单张图片已下载,则执行闭包
        group.notify(queue: DispatchQueue.global(), execute: {
            
            //计算cell的高度
            for viewModel in viewModelsArray {
                viewModel.caculateRowHeigh()
            }
            
            DispatchQueue.main.async {
                //执行成功闭包
                callBack(true)
            }
            
        })
        
    }
    
}
